package homework;

/**
 * @author DCSGO
 * @version 1.0
 * (1)有2个用户分别从同一个卡上取钱(总额:10000)
 * (2)每次都取1000,当余额不足时，就不能取款了
 * (3)不能出现超取现象 -> 线程同步问题
 */
public class Homework02 {
    public static void main(String[] args) {
        User user = new User();
        new Thread(user).start();
        new Thread(user).start();
        /*
         * Thread-0取了1000 money = 9000
         * Thread-1取了1000 money = 8000
         * Thread-1取了1000 money = 7000
         * Thread-0取了1000 money = 6000
         * Thread-1取了1000 money = 5000
         * Thread-0取了1000 money = 4000
         * Thread-1取了1000 money = 3000
         * Thread-0取了1000 money = 2000
         * Thread-0取了1000 money = 1000
         * Thread-1取了1000 money = 0
         * 钱已经不够取了 money = 0
         * 钱已经不够取了 money = 0
         *
         * 进程已结束，退出代码为 0
         */
    }
}

class User implements Runnable {
    private int money = 10000;

    public synchronized boolean withdrawMoney() {
        if (money >= 1000) {
            money -= 1000;
            System.out.println(Thread.currentThread().getName() + "取了1000 " + "money = " + money);
            return true;
        }
        return false;
    }

    @Override
    public void run() {
        while (withdrawMoney()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("钱已经不够取了 money = " + money);
    }
}
